#include "main.h"

// Rotary encoder inputs
InterruptIn encoder_clk(PA_0);
DigitalIn encoder_dt(PA_4);

// Counter for encoder (not used here)
int count_time = 0;

// Encoder interrupt service routine
void encoder_isr() {
    static int last_dt_state = 0;
    
    int current_clk_state = encoder_clk.read();
    int current_dt_state = encoder_dt.read();

    // Check direction of rotation
    if (current_clk_state == 1 && last_dt_state != current_dt_state) {  
        if (current_dt_state == 1) {
            // Clockwise rotation: increase value
            if (setting_index == 0 && volume_level < 10)
                volume_level++;
            else if (setting_index == 1 && brightness_level < 10)
                brightness_level++;
            else if (setting_index == 2 && difficulty_level < 10)
                difficulty_level++;
        } else {
            // Counter-clockwise rotation: decrease value
            if (setting_index == 0 && volume_level > 0)
                volume_level--;
            else if (setting_index == 1 && brightness_level > 0)
                brightness_level--;
            else if (setting_index == 2 && difficulty_level > 0)
                difficulty_level--;
        }
    } 
    else if (current_clk_state == 0 && last_dt_state != current_dt_state) { 
        if (current_dt_state == 1) {
            if (setting_index == 0 && volume_level > 0)
                volume_level--;
            else if (setting_index == 1 && brightness_level > 0)
                brightness_level--;
            else if (setting_index == 2 && difficulty_level > 0)
                difficulty_level--;
        } else {
            if (setting_index == 0 && volume_level < 10)
                volume_level++;
            else if (setting_index == 1 && brightness_level < 10)
                brightness_level++;
            else if (setting_index == 2 && difficulty_level < 10)
                difficulty_level++;
        }
    }
    last_dt_state = current_dt_state; // Update last DT state
}

// Initialize encoder interrupt
void encoder_init() {
    encoder_clk.fall(&encoder_isr); 
    encoder_clk.rise(&encoder_isr);  
}

// Apply new brightness setting
void setting_change()
{
    lcd.setBrightness(brightness_level / 10.0);
}
